package com.ddone.demo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author ddone
 * @date 2024/3/23-15:14
 * 铭感词 拦截器
 */
public class SensitiveInterceptor implements HandlerInterceptor {
    /**
     * 调用完方法后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView 有可能为null 添加@ResponseBody 返回Json时可能为空
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        Optional.ofNullable(modelAndView)
                .map(ModelAndView::getModel)
                .map(model->(String)model.get("message"))
                .filter(message-> message.contains("敏感词"))
                .ifPresent(message->modelAndView.addObject("message",message.replaceAll("敏感词", "***")));
    }
}
